<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    public function index(){
        $User = M("User"); // 实例化User对象
        $data = $User->select();
        $this->assign('list',$data);
        $this->display();
        //dump($data);
    }

    public function add(){
        $User = M("groups"); // 实例化User对象
        $data = $User->select();
        $this->assign('list',$data);
        $this->display();
    }

    public function insert(){
        $post = $_POST;
        $User = M("User"); // 实例化User对象
        $data['iden'] = $post['iden'];
        $data['name'] = $post['name'];
        $data['sex'] = $post['sex'];
        $data['groups'] = implode(',',$post['group']);
        $data['images'] = $post['images'];
        $id = $User->data($data)->add();
        if(!empty($data['groups'])){
            $Group = M('Groups');
            $link = M('UserGroup');
            foreach($post['group']  as $k=>$v){
                $groupdata = $Group->find($v);
                $Group->nums = $groupdata['nums'] + 1;
                $Group->where('id='.$v)->save();

                $linkdata['uid'] = $id;
                $linkdata['gid'] = $v;
                $link->data($linkdata)->add();
            }

        }

        $this->redirect('user/index');
        //dump($data);
    }

    public function detail(){
        $id = $_GET['id'];
        $User = M("User"); // 实例化User对象
        $data = $User->where('id='.$id)->find();
        //dump($data);exit;
        $this->assign('list',$data);
        $this->display();

    }

    public function edit(){
        $id = $_GET['id'];
        $User = M("User"); // 实例化User对象
        $data = $User->where('id='.$id)->find();
        $this->assign('list',$data);
        $this->display();

    }

    public function update(){
        $post = $_POST;
        $User = M("User"); // 实例化User对象
        $id = $post['id'];
        $data['iden'] = $post['iden'];
        $data['name'] = $post['name'];
        $data['sex'] = $post['sex'];
        $data['groups'] = implode(',',$post['group']);
        $data['images'] = $post['images'];
        $User->where('id='.$id)->save($data);
        $this->redirect('user/index');
    }
}